package com.vitabuybuy.tv.ui.mine.talent.task

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityInviteTaskDetailBinding
import com.vitabuybuy.tv.dialog.RefuseInvitePopup
import com.vitabuybuy.tv.dto.AddressListDto
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.toast.XToast
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.ui.mine.address.AddressActivity
import com.vitabuybuy.tv.ui.mine.talent.task.adapter.TaskGoodAdapter
import com.vitabuybuy.tv.ui.mine.talent.task.viewmodel.TaskDetailsViewModel
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import kotlinx.android.synthetic.main.activity_invite_task_detail.*

class InviteTaskDetailActivity :
    BaseActivity<TaskDetailsViewModel, ActivityInviteTaskDetailBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_invite_task_detail

    private var mTtaskId :Int?= -1
    private val goodAdapter by lazy { TaskGoodAdapter(false) }
    private var defaultAddId = -1

    override fun onGetBundle(bundle: Bundle?) {
        mTtaskId = bundle?.getInt("mTtaskId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.task_detail))
        mBinding.viewModel = viewModel
        lvGoods.apply {
            adapter = goodAdapter
            layoutManager = LinearLayoutManager(mContext)
            isNestedScrollingEnabled = false
        }
    }

    override fun observeData() {
        viewModel.getTaskMenagerDetails(mTtaskId)
        viewModel.taskMenageDetails.observe(this, Observer {
            tvName.text = it.task.store.name
            tvRequirement.text = it.task.title
            tvRequirementContent.text = String.format(
                getString(R.string.task_requirement), it.task.content
            )
            if (it.task.type == "种草") {
                tvLiveTypeRequirement.visibility = View.GONE
            } else {
                tvLiveTypeRequirement.visibility = View.VISIBLE
                tvLiveTypeRequirement.text =
                    String.format(getString(R.string.live_type_1), it.task.liveType)
            }
            tvAreaRequirement.text =
                String.format(getString(R.string.area_requirement), it.task.label.name)
            tvFansRequirement.text =
                String.format(getString(R.string.fans_requirement), it.task.fansQuantity)
            goodAdapter.setNewData(it.task.productList)
            if (it.address != null) {
                tvAddressName.text = it.address.name
                tvReceiverPhone.text = it.address.phone
                tvReceiverAddressDetail.text = it.address.detail
                defaultAddId = it.address.id
            }
            when(it.status){
                "invitation"->{
                    tvStatus.visibility = View.GONE
                    llHandler.visibility = View.VISIBLE
                }
                "pass"->{
                    tvStatus.visibility = View.VISIBLE
                    llHandler.visibility = View.GONE
                    tvStatus.text = getString(R.string.already_pass)
                }
                "refuse"->{
                    tvStatus.visibility = View.VISIBLE
                    llHandler.visibility = View.GONE
                    tvStatus.text = getString(R.string.already_refuse)
                }
                "partner"->{
                    tvStatus.visibility = View.VISIBLE
                    llHandler.visibility = View.GONE
                    tvStatus.text = getString(R.string.already_push_partner)
                }
            }
        })
    }

    override fun eventHandling() {
        mBinding.btnChatNow.setOnClickListener {
            viewModel.taskMenageDetails.value?.run {
                val chatInfo = ChatInfo()
                chatInfo.type = TIMConversationType.C2C
                chatInfo.id = this.task.store.id.toString()
                chatInfo.chatName = this.task.store.name
                ChatActivity.openActivity(mContext, chatInfo)
            }
        }
        rlreceiverAddress.setOnClickListener {
            AddressActivity.openActivity(mContext, 10002)
        }
        btnRefuse.setOnClickListener {
            RefuseInvitePopup(mContext) { content ->
                val params = HashMap<String, Any?>()
                params["pass"] = false
                params["taskId"] = viewModel.taskMenageDetails.value?.task?.id
                params["refuseReason"] = content
                viewModel.refuseOrAgreeInvite(params)
            }.showPopupWindow()
        }
        btnAgree.setOnClickListener {
            if (defaultAddId == -1) {
                XToast.normal(getString(R.string.please_select_delivery_address))
                return@setOnClickListener
            }
            AlertDialog.Builder(mContext)
                .setTitle(getString(R.string.reminder))
                .setMessage(getString(R.string.are_you_sure_agree))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                    val params = HashMap<String, Any?>()
                    params["pass"] = true
                    params["taskId"] = viewModel.taskMenageDetails.value?.task?.id
                    params["address"] = mapOf(Pair("id", defaultAddId))
                    viewModel.refuseOrAgreeInvite(params)
                }
                .setNegativeButton(getString(R.string.cancel), null).create().show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 10002) {
            val addressDto = data?.extras?.getSerializable("addressDto") as AddressListDto
            defaultAddId = addressDto.id
            tvAddressName.text = addressDto.name
            tvReceiverPhone.text = addressDto.phone
            tvReceiverAddressDetail.text = addressDto.detail
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                viewModel.getTaskMenagerDetails(mTtaskId)
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, mTtaskId: Int) {
            mContext.startActivity(
                bundleOf(Pair("mTtaskId", mTtaskId)),
                InviteTaskDetailActivity::class.java
            )
        }
    }
}
